#!/usr/bin/env python3
import subprocess
import difflib
import sys
import os

def main():
    print("Comparing 'cargo run text.sy' output with target.txt...")
    
    # Run the command and save the output to a temporary file
    # We'll use direct OS commands to make sure we capture the output properly
    os.system('cd /home/matrix/compiler && cargo run text.sy > /tmp/full_output.txt 2>&1')
    
    # Read the full output
    with open('/tmp/full_output.txt', 'r') as f:
        full_output = f.read()
    
    # Extract just the compiler output (after the "Running" line)
    lines = full_output.split('\n')
    compiler_output_lines = []
    found_running = False
    
    for line in lines:
        if 'Running `target/debug/compiler text.sy`' in line:
            found_running = True
            continue
        if found_running:
            compiler_output_lines.append(line)
    
    compiler_output = '\n'.join(compiler_output_lines).rstrip()
    
    # Read the target.txt file
    with open('/home/matrix/compiler/target.txt', 'r') as f:
        target_content = f.read().rstrip()
    
    # Print output lengths for debugging
    print(f"\nCompiler output length: {len(compiler_output)} characters")
    print(f"Target.txt length: {len(target_content)} characters")
    
    # Save the compiler output to a file for inspection
    with open('/tmp/compiler_output.txt', 'w') as f:
        f.write(compiler_output)
    
    # Check if the contents are identical
    if compiler_output == target_content:
        print("\nNo differences found! The output matches target.txt exactly.")
        return
    
    # Create a diff
    diff = list(difflib.unified_diff(
        target_content.splitlines(),
        compiler_output.splitlines(),
        fromfile='target.txt',
        tofile='compiler output',
        lineterm=''
    ))
    
    # Print the differences
    if diff:
        print("\nDifferences found:")
        for line in diff[:50]:  # Limit to first 50 diff lines
            print(line)
        
        if len(diff) > 50:
            print(f"... and {len(diff) - 50} more differences")
        
        # Count differences by type
        additions = sum(1 for line in diff if line.startswith('+') and not line.startswith('+++'))
        deletions = sum(1 for line in diff if line.startswith('-') and not line.startswith('---'))
        print(f"\nSummary: {additions} additions, {deletions} deletions")
        
        # Create a detailed comparison file
        with open('/tmp/comparison.txt', 'w') as f:
            f.write("TARGET.TXT | COMPILER OUTPUT\n")
            f.write("=" * 80 + "\n")
            
            target_lines = target_content.splitlines()
            compiler_lines = compiler_output.splitlines()
            
            max_lines = max(len(target_lines), len(compiler_lines))
            for i in range(max_lines):
                target_line = target_lines[i] if i < len(target_lines) else ""
                compiler_line = compiler_lines[i] if i < len(compiler_lines) else ""
                f.write(f"{target_line[:40]:<40} | {compiler_line[:40]}\n")
        
        print(f"\nA detailed comparison has been saved to /tmp/comparison.txt")

if __name__ == "__main__":
    main()
